<template>
  <div class="box">
    <div class="leftBox">
      <div v-for="(item, index) in list" class="item" @click="webSocketHanler(item.sid)" :key="index">
        <el-avatar size="small" ></el-avatar>
        <p>{{item.xingming}}</p>
      </div>
    </div>
    <div class="rightBox">
      <websocket :socket="socket" />
    </div>
  </div>
</template>

<script>
import websocket from "@/views/modules/liaotian/websocket.vue";

export default {
  components: {websocket},
  data() {
    return {
      reqUrl: `http://localhost:8080/springboot3634x/websocket/${this.$storage.get("adminName")}`,
      socket: null,
      list: [],
      currentSid: -1
    };
  },
  mounted() {
    this.initWebSocket()
    this.initList()
  },
  methods: {
    initWebSocket() {
      if (typeof WebSocket == "undefined") {
        this.$message("您的浏览器不支持在线聊天")
      } else {
        this.socket = new WebSocket(this.reqUrl.replace("http", "ws"));
        this.socket.onopen = () => {
          this.$message({
            showClose: true,
            message: 'Socket 已打开',
            type: 'success'
          })
          this.currentSid = this.$storage.get("adminName")
        };
        this.socket.onmessage = (msg) => {
          let msgs = msg.data.split('-')

          if (this.currentSid !== msgs[0]) {
            this.list.push({
              sid: msgs[0],
              xingming: msgs[0]
            })
          }
          this.$store.commit('websocket/addMsg', {sid: msgs[0], text: msgs[1], clazz: 'left'})
        };
        this.socket.onclose = () => {
          this.$message({
            showClose: true,
            message: 'Socket已关闭',
            type: 'warning'
          })
        };
        this.socket.onerror = () => {
          this.$message({
            showClose: true,
            message: 'Socket发生了错误',
            type: 'error'
          })
        };
      }
    },
    initList() {
      this.$http({
        url: `liaotian/onlineYishi`,
        method: 'get'
      }).then(res => {
        this.list = res.data.data.map(item => {
          return {
            sid: item.yonghuming,
            xingming: item.yonghuming
          }
        })
      })
    },
    webSocketHanler(e) {
      // this.sid = e
      this.currentSid = e
      this.$bus.$emit('clearMessages', e)
    }
  },
};
</script>
<style lang="scss" scoped>
.box {
  display: flex;

  .leftBox {
    height: calc(100vh - 60px - 14vh);
    width: 20%;
    background-color: pink;

    .item {
      display: flex;
      align-items: center;
      padding-left: 16px;
      height: 60px;
      background-color: #cacaca;
      cursor: pointer;
    }

    .item:nth-child(2n) {
      background-color: #f6f6fa;
    }
  }

  .rightBox {
    display: flex;
    align-items: center;
    height: calc(100vh - 60px - 14vh);
    width: 80%;
    background-color: skyblue;

  }
}
</style>
